/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lottoapp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Mark
 */
public class LottoFetcher {
    public static LottoResult fetchLotto() throws IOException{
        String url = "http://www.nationale-loterij.be/NL/Spelen_en_Winnen/Trekkingsspelen/Lotto/default.aspx/?cid=/Sea/NL/Google_Adwords-cpc-tirage%28corp%29/Lotto/Recruit-na-txt///03042010&gclid=CPH41aPnr7oCFYdd3godkXoAhQ";
       
        Document doc = Jsoup.connect(url).get();
        String title = getDateFrom(doc);
      
        List<Integer> numbers = getNumberFrom(doc);
        Set<Integer> nrSet=new HashSet<>();
        nrSet.addAll(numbers);
        LottoResult lottoResult = LottoResult.createWithDateAndNumbers(title,nrSet);
        return lottoResult;
    }

    private static List<Integer> getNumberFrom(Document doc) throws NumberFormatException {
        String clazz= "resultBall";
        Elements table=doc.getElementsByClass(clazz);
        Element tableElement =table.get(0);        
        Elements numbers = tableElement.getElementsByTag("td");
        List<Integer> result = new ArrayList<>();
        for(int i=0;i<numbers.size();i++){
            String numTxt =numbers.get(i).text();
            Integer nr = Integer.valueOf(numTxt);
            result.add(nr);
        }
        return result;
    }

    private static String getDateFrom(Document doc) {
        String clazz= "jg_DateLastResult";
        Elements table=doc.getElementsByClass(clazz);
        Element tableElement =table.get(0);        
        return tableElement.text();
    }
}
